#pragma once 
#include "socket.hpp"
#include "eventloop.hpp"

//对Socket服务端accept的封装
class Acceptor
{
private:
    using AcceptCallBack = std::function<void(int)>;

    // 将服务端套接字的 accept 设为读事件，当启动读事件监控时，就会不断 accept 客户端的 connect 连接
    void HandleRead()
    {
        int newfd = _socket.Accept();
        if(newfd < 0)
            return ;
        if(_accept_callback)
            _accept_callback(newfd);
    }

    int CreateServer(int port)
    {
        assert(_socket.CreateServer(port) == true);
        return _socket.GetFd();
    }
public:
    Acceptor(EventLoop* loop, int port)
    :_socket(CreateServer(port)), _loop(loop), _channel(loop, _socket.GetFd())
    {
        _channel.SetReadCallBack(std::bind(&Acceptor::HandleRead, this));
    }

    void SetAcceptCallBack(const AcceptCallBack& accpet_cb)
    {
        _accept_callback = accpet_cb;
    }

    void Listen()
    {
        _channel.EnableRead();
    }

private:
    Socket _socket;
    EventLoop* _loop;
    Channel _channel;
    AcceptCallBack _accept_callback;
};